﻿using Dt261.Model;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dt261.db
{
    class ResultDataSetDb
    {
        private readonly SQLiteConnection connection;

        public ResultDataSetDb(string dbPath)
        {
            connection = new SQLiteConnection(dbPath);
            connection.CreateTable<ResultDataSet>();
        }

        public int AddResultDataSet(ResultDataSet m)
        {

            return connection.Insert(new ResultDataSet()
            {
                Uid=m.Uid,
                HeadsetMode = m.HeadsetMode,
                IsLine=m.IsLine,
                IsRight = m.IsRight,
                PainStrokeWidth = m.PainStrokeWidth,
                PaintColor = m.PaintColor,
                PointRadius = m.PointRadius,
                ResultId = m.ResultId
            });

             //connection.Query("select last_insert_rowid() from ResultDataSet", null);
        }

        public int UpdateResultDataSet(ResultDataSet m)
        {

            IList<ResultDataSet> list = connection.Query<ResultDataSet>("select * from ResultDataSet where id = ?", m.Id);

            if (list.Count() > 0)
            {
                return connection.Update(m);
            }
            else
            {
                return this.AddResultDataSet(m);
            }
        }

        public IList<ResultDataSet> GetResultDataSets()
            => connection.Table<ResultDataSet>().ToList();

        public IList<ResultDataSet> GetResultDataSetrByUid(string uid)
        {
            IList<ResultDataSet> list = connection.Query<ResultDataSet>("select * from ResultDataSet where uid = ?", uid);

            return list;
        }

        public IList<ResultDataSet> GetResultDataSetrById(int id)
        {
            IList<ResultDataSet> list = connection.Query<ResultDataSet>("select * from ResultDataSet where id = ?", id);

            return list;
        }
        public IList<ResultDataSet> GetResultDataSetsByResultId(string rid)
        {
            IList<ResultDataSet> list = connection.Query<ResultDataSet>("select * from ResultDataSet where ResultId = ?", rid);

            return list;
        }

        public ResultDataSet GetOneResultDataSetByUid(string uid)
        {
            IList<ResultDataSet> list = connection.Query<ResultDataSet>("select * from ResultDataSet where uid = ?", uid);

            return list.Count() > 0 ? list[0] : null;
        }

        public ResultDataSet GetOneResultDataSetByUid(int id)
        {
            IList<ResultDataSet> list = connection.Query<ResultDataSet>("select * from ResultDataSet where id = ?", id);

            return list.Count() > 0 ? list[0] : null;
        }

        public int DeleteUser(ResultDataSet m)
        {
            return connection.Delete(m);
        }
    }
}
